import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { MenuService, SettingsService, TitleService, ALAIN_I18N_TOKEN } from '@delon/theme';
import { ACLService } from '@delon/acl';
import { TranslateService } from '@ngx-translate/core';
import { I18NService } from '../i18n/i18n.service';

import { NzIconService } from 'ng-zorro-antd';
import { ICONS_AUTO } from '../../../style-icons-auto';
import { ICONS } from '../../../style-icons';

import { APP_DATA } from './app-data';
import { I18N_DATA } from './i18n-data';
import { CacheService } from '@delon/cache';
import { UserDTO } from 'src/app/benshuo/model/user-dto';
import { ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
  constructor(
    iconSrv: NzIconService,
    private menuService: MenuService,
    private translate: TranslateService,
    @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
    private settingService: SettingsService,
    private aclService: ACLService,
    private titleService: TitleService,
    private httpClient: HttpClient,
    private cacheService: CacheService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
  ) {
    iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
  }

  private viaLocal(resolve: any, reject: any) {
    // only works with promises
    // https://github.com/angular/angular/issues/15088
    // setting language data
    this.translate.setTranslation(this.i18n.defaultLang, I18N_DATA);
    this.translate.setDefaultLang(this.i18n.defaultLang);

    // application data
    const res: any = APP_DATA;

    // 获取缓存中的权限
    const userDTO: UserDTO = this.cacheService.get('__user', { mode: 'none' });
    if (userDTO) {
      // 用户信息：包括姓名、头像、邮箱地址
      this.settingService.setUser({
        name: userDTO.name,
        id: userDTO.id,
      });

      // ACL：设置权限
      this.aclService.setRole(userDTO.authorities);
      // this.aclService.setAbility(auth);
    } else {
      this.tokenService.clear();
    }

    this.menuService.add(res.menu);

    // 设置页面标题的后缀
    this.titleService.suffix = res.app.name;
    // 应用信息：包括站点名、描述、年份
    this.settingService.setApp(res.app);

    resolve(null);
  }

  load(): Promise<any> {
    return new Promise((resolve, reject) => {
      this.viaLocal(resolve, reject);
    });
  }
}
